package com.lebang.controller.sys;

import com.alibaba.fastjson.JSONObject;
import com.lebang.common.Login;
import com.lebang.entity.ConfigurationRecord;
import com.lebang.feign.AppInfoFeign;
import com.lebangweb.common.TextUtil;
import com.lebangweb.response.JsonData;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;



/**
 * upload_img_record
 *
 * @author hwq
 * @date 2020-10-20
 */
@Controller
@RequestMapping("/sys/configurationrecord")
public class ConfigurationRecordController {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private AppInfoFeign appInfoFeign;

    @Login
    @GetMapping("/list")
    public String list(Model model) {
        JsonData list = appInfoFeign.list();
        model.addAttribute("appInfoList", list.getData());
        return "/configurationrecord/list";
    }




    @Login
    @ApiOperation(value = "分页")
    @PostMapping("/list")
    @ResponseBody
    public JSONObject list(HttpServletRequest request,
                           @RequestParam Integer page,
                           @RequestParam Integer limit,
                           @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime star,
                           @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime end,
                           String configName,Integer appId
    ) {
        JSONObject jsonObject=new JSONObject();
        int pageSize = (page - 1) * limit;
        Query query=new Query();
        if (!TextUtil.isEmpty(star) || !TextUtil.isEmpty(end)){
            Criteria criteria = new Criteria();
            criteria.andOperator(Criteria.where("createTime").gte(star),Criteria.where("createTime").lte(end));
            query.addCriteria(criteria);
        }
        if(!TextUtil.isEmpty(appId)){
            query.addCriteria(Criteria.where("appId").is(appId));
        }
        if (!TextUtil.isEmpty(configName)){
            query.addCriteria(Criteria.where("configName").regex(configName));
        }
        jsonObject.put("count", mongoTemplate.count(query,ConfigurationRecord.class));
        query.skip(pageSize);
        query.limit(limit);
        query.with(Sort.by(Sort.Order.desc("createTime")));
        jsonObject.put("code", 0);
        jsonObject.put("data", mongoTemplate.find(query, ConfigurationRecord.class));
        return jsonObject;
    }
}
